<template>
  <div class="employee-list">
    <!-- 筛选区域 -->
    <div class="filter-section">
      <div class="filter-item">
        <span>员工</span>
        <el-input
            v-model="searchInput"
            placeholder="请输入姓名/电话"
            clearable
            style="width: 200px"
        />
      </div>
      <div class="filter-item">
        <span>请选择门店</span>
        <el-select
            v-model="selectedStore"
            placeholder="请选择门店"
            clearable
            style="width: 150px"
        >

          <el-option
              v-for="store in stores"
              :key="store.value"
              :label="store.label"
              :value="store.value"
          />
        </el-select>
      </div>

      <div class="filter-item">
        <el-button type="primary" @click="handleSearch">查询</el-button>
      </div>
    </div>
    <!-- 新增/编辑弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑员工' : '新增员工'"
        width="500px"
    >
      <el-form
          :model="formData"
          ref="employeeForm"
          label-width="80px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="职责" prop="role">
          <el-select v-model="formData.role" placeholder="请选择职责">
            <el-option
                v-for="role in roles"
                :key="role.value"
                :label="role.label"
                :value="role.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="门店" prop="store">
          <el-select v-model="formData.storeId" placeholder="请选择门店">
            <el-option
                v-for="store in stores"
                :key="store.value"
                :label="store.label"
                :value="store.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 数据列表区域 -->
    <div class="data-section">
      <div class="data-header">
        <span>数据列表</span>
        <el-button type="primary" @click="addEmployee">新增员工</el-button>
      </div>
      <div class="table-section">
        <el-table
            :data="tableData"
            border
            style="width: 100%"
            @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="工号" width="80" />
          <el-table-column prop="name" label="姓名" width="100" />
          <el-table-column prop="phone" label="联系方式" width="150" />
          <el-table-column prop="store" label="所属门店" width="150" />
          <el-table-column prop="creatTime" label="入职日期" width="120" />
          <el-table-column prop="role" label="岗位名称" width="120" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-section">
        <div class="pagination-info">共 {{ totalPage }} 页/{{ totalData }} 条数据</div>
        <el-pagination
            v-model:current-page="currentPage"
            :page-count="totalPage"
            layout="prev, pager, next"
            @current-change="handlePageChange"
        />
        <div class="batch-actions">
          <el-checkbox v-model="selectAll">全选</el-checkbox>
          <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from "axios";

const selectedIds = ref([])
const dialogVisible = ref(false);
const isEdit = ref(false);
const employeeForm = ref(null);
const roles = ref([

]);


const currentTime = new Date().toISOString();

const formData = ref({
  id: '',
  name: '',
  phone: '',
  role: '',

  creatTime: currentTime
});


// 模拟数据
const stores = ref([
]);

const statuses = ref([
  { value: '1', label: '启用' },
  { value: '0', label: '禁用' },
]);

// 表格数据
const tableData = ref([
]);

// 弹窗的确认
const handleSubmit = () => {
  if (isEdit.value) {
    axios.post(`/employ/updateEmployee/${formData.value.id}`, formData.value)
        .then(res => {
          ElMessage.success(res.data.msg);
          dialogVisible.value = false;
          initData();
        }).catch(err => {
      ElMessage.error('修改失败');
    });
  }else{
    axios.post(`/employ/addEmploy`, formData.value)
        .then(res => {
          ElMessage.success(res.data.msg);
          dialogVisible.value = false;
          initData();
        }).catch(err => {
          ElMessage.error('新增失败');
    });
  }


};
// 筛选条件
const searchInput = ref('');
const selectedStore = ref('');
const selectedStatus = ref('');

// 分页
const currentPage = ref(1);
const totalPage = ref(10);
const totalData = ref(100);

// 选择的行
const selectedRows = ref([]);

// 全选
const selectAll = ref(false);

// 筛选
function handleSearch() {
  const searchParams = {
    search: searchInput.value, // 获取搜索关键词
    storeId: selectedStore.value // 获取选择的门店ID
  };

  axios.post(`/employ/search/${currentPage.value}/8`, searchParams)
      .then(res => {
        if(res.data.code === 200) {
          tableData.value = res.data.obj.records;
          totalData.value = res.data.obj.total;
          totalPage.value = res.data.obj.pages;
        } else {
          ElMessage.error(res.data.msg || '搜索失败');
        }
      })
      .catch(err => {
        ElMessage.error('请求异常，请检查网络');
        console.error('搜索请求异常:', err);
      });
}


// 查看
function handleView(row) {
  ElMessage.info(`查看员工 ${row.name} 的详细信息`);
}

// 编辑
const handleEdit = (row) => {
  isEdit.value = true;
  formData.value = {
    id: row.id,
    name: row.name,
    phone: row.phone,
    role: row.roleValue || '1', // 需要根据实际数据结构调整
    store: row.storeValue || '1' // 需要根据实际数据结构调整
  };
  dialogVisible.value = true;
};

// 删除
function handleDelete(row) {
  ElMessageBox.confirm(`确定要删除员工 ${row.name} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(() => {
        axios.delete(`/employ/deleteEmploy/${row.id}`).then(()=>{
              ElMessage.success('删除成功');
              initData()
        });
      })
      .catch((err) => {
        ElMessage.info('已取消删除');
      });
}
function handleSelectionChange(selection) {
  selectedRows.value = selection;
  // 新增：提取选中行的 ID 到 selectedIds
  selectedIds.value = selection.map(row => row.id); // 根据实际数据结构调整 row.id
  selectAll.value = selection.length === tableData.value.length;
}
// 批量删除
const handleBatchDelete =()=>{
  console.log({data: selectedIds.value});
  axios.delete("/employ/deleteChoises", {data: selectedIds.value}).then(res=>{
  ElMessage.success("成功删除项");
  initData();
  })

}

// 获取店名
const getStoreName=()=>{
  axios.get(`/store/getStoreName`).then(res => {
    // 将返回的数组对象转换为element需要的格式
    stores.value = res.data.map(item => ({
      value: item.id,
      label: item.name
    }));
  });
}

// 获取职责名单
const getRoleName=()=>{
  axios.get(`/role/getAll`).then(res => {
    console.log(res.data.obj);
    roles.value = res.data.obj.map(item => ({
      value: item.id,
      label: item.roleName
    }));
  });
}
// 新增员工
const addEmployee = () => {
  isEdit.value = false;
  formData.value = {
    id: '',
    name: '',
    phone: '',
    role: '',
    store: ''
  };
  axios.get(`/store/getStoreName`).then(res => {
    // 将返回的数组对象转换为element需要的格式
    stores.value = res.data.map(item => ({
      value: item.id,
      label: item.name
    }));
  });
  axios.get(`/role/getAll`).then(res => {
    console.log(res.data.obj);
    roles.value = res.data.obj.map(item => ({
      value: item.id,
      label: item.roleName
    }));
  });
  dialogVisible.value = true;
};

// 分页变化
function handlePageChange(page) {
  currentPage.value = page;
  initData();
}


// 初始化方法
const initData = ()=>{
  axios.get(`/employ/getAll/${currentPage.value}/8`).then(resp=>{
    console.log(resp.data)
    tableData.value = resp.data.obj.records;
    totalData.value = resp.data.obj.total
    totalPage.value = resp.data.obj.pages
  })
}

onMounted(()=>{
  initData();
  getStoreName();
  getRoleName();

})
// 全选变化
watch(selectAll, (val) => {
  const currentTableData = tableData.value;
  if (val) {
    // 全选时同时更新 selectedIds
    selectedRows.value = [...currentTableData];
    selectedIds.value = currentTableData.map(row => row.id); // 同步 ID
  } else {
    selectedRows.value = [];
    selectedIds.value = []; // 清空 ID
  }
});

</script>

<style scoped>
.employee-list {
  padding: 20px;
}

.filter-section {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 20px;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.data-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.pagination-info {
  font-size: 14px;
  color: #666;
}

.batch-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}
</style>